package com.cjl.net.google;

import android.content.Context;

import com.cjl.net.Config;
import com.cjl.net.Request;
import com.cjl.net.Response;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUrlConnectClient implements Request {
    @Override
    public void request(Context context, Config config, String strUrl, Response response) {

        try {
            URL url = new URL(strUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(config.getConnectTimeOut());
            urlConnection.setReadTimeout(config.getReadTimeOut());
            urlConnection.setRequestMethod(config.getMethod());

            InputStream inputStream = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null){
                result.append(line);
            }
            response.success(result);


        } catch (MalformedURLException e) {
            e.printStackTrace();
            response.fail(e);
        } catch (IOException e) {
            e.printStackTrace();
            response.fail(e);
        }
    }
}
